package com.tennis.tennisreservation.service.impl;

import com.tennis.tennisreservation.entity.Image;
import com.tennis.tennisreservation.repository.ImageRepository;
import com.tennis.tennisreservation.service.ImageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 图片服务实现类
 */
@Service
public class ImageServiceImpl implements ImageService {

    private static final Logger logger = LoggerFactory.getLogger(ImageServiceImpl.class);
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");

    @Value("${file.upload-dir:./uploads}")
    private String uploadDir;

    @Value("${file.access-path:/uploads/}")
    private String accessPath;

    @Autowired
    private ImageRepository imageRepository;

    @Override
    @Transactional
    public Image uploadImage(MultipartFile file, String type) {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传的文件不能为空");
        }

        try {
            // 获取文件名和扩展名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            // 检查是否是图片
            if (!isImageFile(extension)) {
                throw new IllegalArgumentException("只允许上传图片文件(jpg,jpeg,png,gif)");
            }

            // 创建日期目录
            String dateDir = LocalDateTime.now().format(DATE_FORMATTER);
            String relativePath = dateDir + "/";
            
            // 创建目录
            Path uploadPath = Paths.get(uploadDir, dateDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 生成新文件名（防止重复）
            String newFilename = UUID.randomUUID().toString() + extension;
            String filePath = relativePath + newFilename;
            
            // 保存文件
            Path targetPath = Paths.get(uploadDir, filePath);
            Files.copy(file.getInputStream(), targetPath);

            // 创建图片记录
            Image image = new Image();
            image.setUrl(accessPath + filePath);
            image.setType(type);
            image.setCreateTime(LocalDateTime.now());

            return imageRepository.save(image);
        } catch (IOException e) {
            logger.error("上传图片失败", e);
            throw new RuntimeException("上传图片失败: " + e.getMessage());
        }
    }

    @Override
    public Image getImageById(Long id) {
        return imageRepository.findById(id).orElse(null);
    }

    @Override
    public List<Image> getImagesByType(String type) {
        if (StringUtils.hasText(type)) {
            return imageRepository.findByType(type);
        }
        return imageRepository.findAll();
    }

    @Override
    public Map<String, Object> getImageList(int page, int size, String type) {
        Pageable pageable = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.DESC, "createTime"));
        
        Page<Image> pageResult;
        if (StringUtils.hasText(type)) {
            pageResult = imageRepository.findByType(type, pageable);
        } else {
            pageResult = imageRepository.findAll(pageable);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("list", pageResult.getContent());
        result.put("total", pageResult.getTotalElements());
        
        return result;
    }

    @Override
    @Transactional
    public boolean deleteImage(Long id) {
        Image image = imageRepository.findById(id).orElse(null);
        if (image == null) {
            return false;
        }

        try {
            // 删除物理文件
            String fileUrl = image.getUrl();
            if (fileUrl.startsWith(accessPath)) {
                String relativePath = fileUrl.substring(accessPath.length());
                Path filePath = Paths.get(uploadDir, relativePath);
                Files.deleteIfExists(filePath);
            }
            
            // 删除数据库记录
            imageRepository.deleteById(id);
            return true;
        } catch (IOException e) {
            logger.error("删除图片文件失败", e);
            return false;
        }
    }

    /**
     * 检查文件扩展名是否为图片
     */
    private boolean isImageFile(String extension) {
        if (extension == null || extension.isEmpty()) {
            return false;
        }
        
        String ext = extension.toLowerCase();
        return ext.equals(".jpg") || ext.equals(".jpeg") || 
               ext.equals(".png") || ext.equals(".gif");
    }
}
